#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@date: 2011-11-08
@author: shell.xu
'''
import os, sys, datetime
import tmpl
import pymongo
import comment
from bson.objectid import ObjectId
from utils import *

articles = web.config.db['articles']
articles.ensure_index('author')

PAGE_LIMIT = 5

class list_user(object):
    ''' 列出用户 '''
    def GET(self, username):
        artlist = articles.find({'author': username})
        artlist = artlist.sort('ctime', pymongo.DESCENDING).limit(PAGE_LIMIT)
        return calltmpl(tmpl.atc.list, articles = artlist)

class list_all(object):
    ''' 列出所有用户 '''
    def GET(self):
        artlist = articles.find().sort('ctime', pymongo.DESCENDING)
        return calltmpl(tmpl.atc.list, articles = artlist.limit(PAGE_LIMIT))

class search(object):
    ''' 提交一个keyword，返回满足要求的结果列表 '''
    def GET(self):
        keyword = web.input()['keyword']
        num, matches = zmqreq('search_article', keyword, 0, 20)
        artlist = []
        for did, rank, aid in matches:
            artlist.append(articles.find_one({'_id': ObjectId(aid)}))
        return calltmpl(tmpl.atc.list, articles = artlist, keyword = keyword)
    POST = GET

form_add = form.Form(
    form.Textbox('title',
                 form.Validator("empty title", lambda t:bool(t)),
                 description = 'title'),
    form.Textarea('content',
                  form.Validator("empty content", lambda t:bool(t)),
                  description = 'content', rows = '25', cols = '80'),
    form.Button("submit", type="submit", description="Submit"),
    )

class add(object):
    ''' 添加一个文章 '''
    def GET(self):
        if web.config.sess.get('user', None) is None:
            return web.seeother(web.config.urls.get('user_login'))
        return calltmpl(tmpl.atc.add, form = form_add())

    def POST(self):
        if web.config.sess.get('user', None) is None:
            return web.seeother(web.config.urls.get('user_login'))
        f = form_add()
        if not f.validates(): return calltmpl(tmpl.atc.add, form = form_add())
        atc = form2obj(f, ['title', 'content'],
                       {'author': web.config.sess.user['_id'],
                        'ctime': datetime.datetime.now(),
                        'mtime': datetime.datetime.now(),
                        'cntview': 0, 'cntcmt': 0,
                        'cmtlist': [], 'cmtid': 0})
        aid = str(articles.insert(atc, safe = True))
        btmqsend('update_article', str(aid))
        return web.seeother('%s/%s' % (web.config.urls['atc_show'], aid))

# 此处曾经考虑过，是否和add合并到一起。仔细斟酌后发现重合代码太少，逻辑比较混乱，所以暂时作罢。
class edit(object):
    ''' 修改一个文章 '''
    def GET(self, aid):
        if web.config.sess.get('user', None) is None:
            return web.seeother(web.config.urls.get('user_login'))
        atc = articles.find_one({'_id': ObjectId(aid)})
        if atc is None: return 'article not found'
        f = form_add({'title': atc['title'], 'content': atc['content']})
        return calltmpl(tmpl.atc.add, form = f)

    def POST(self, aid):
        if web.config.sess.get('user', None) is None:
            return web.seeother(web.config.urls.get('user_login'))
        atc = articles.find_one({'_id': ObjectId(aid)})
        if atc is None: return 'article not found'
        if atc['author'] != web.config.sess.user['_id']:
            return 'it\'s not your article'
        f = form_add()
        if not f.validates(): return calltmpl(tmpl.atc.add, form = f)
        atc.update(form2obj(f, ['title', 'content']))
        atc.update({'mtime': datetime.datetime.now()})
        articles.save(atc, safe = True)
        btmqsend('update_article', str(atc['_id']))
        return web.seeother('%s/%s' % (web.config.urls['atc_show'], aid))

class show(object):
    ''' 显示一个文章 '''
    def GET(self, aid):
        atc = articles.find_one({'_id': ObjectId(aid)})
        if atc is None: return 'article not found'
        atc['cntview'] += 1
        articles.save(atc)
        return calltmpl(tmpl.atc.show, atc = atc,
                        sess_user = web.config.sess.get('user', None),
                        cmtform = comment.form_add())
